const LocalStrategy = require('passport-local').Strategy
const WxAppStrategy = require('./wxapp-strategy')
const Passport = require('passport').Passport
const config = require('config')
const utils = require('utility')
const userService = require('../services/user')
const passport = new Passport()
const _ = require('lodash')

passport.serializeUser(function(user, done) {
  done(null, user.id);
})

passport.deserializeUser(async function(id, done) {
  try {
    let user = await userService.findById(id)
    done(null, user)
  } catch (err) {
    done(err)
  }
})

passport.use(new WxAppStrategy(
  async function(wxUser, done) {
    try {
      let user = await userService.findByOpenId(wxUser.openId)
      if (!user) {
        user = await userService.registerByOpenId(wxUser.openId, wxUser)
      }

      return done(null, user)
    } catch (err) {
      done(err)
    }
  }
))

const auth = function (req, res, next) {
  if (req.user) {
    next()
    return
  }

  passport.authenticate('wxapp', {session: true}, function(err, user, info) {
    if (err) { return next(err); }
    if (!user) {
      res.status(401).json(info)
      return
    }

    req.logIn(_.omit(user, ['password']), function(err) {
      if (err) { return next(err) }
      next()
    })

  })(req, res, next)
}

passport.auth = auth

module.exports = passport